<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once ( LIB_DIR.'search/productsearch.php' );
require_once ( LIB_DIR.'classes/Pager.php' );
require_once ( LIB_DIR.'model/ProductDAO.php' );
require_once ( LIB_DIR.'model/ProductCategoryDAO.php' );
require_once ( LIB_DIR.'model/ShopCategoryDAO.php' );

$pageVars = array();

//get city list
//$citydao = GetCityDAO();

//declare global vars
global $cityList,$platformList,$cityMap;

$pageVars['cityList'] = $cityList;
$validSortby = array( "score", "service", "reality", "velocity", "rate", "price", "review_count" );

if( !isset( $_GET['q'] ) ) {
//do nothing, just display
}
else {
	$keyword = htmlspecialchars( $_GET['q'] );

	//not required field
	$category = '';
	if( isset( $_GET['category'] ) )
		$category = $_GET['category'];
	$sortby = '';
	if( !empty( $_GET['sortby'] ) )
		$sortby = $_GET['sortby'];
	else
		$sortby = "score-desc";
	$location = '';
	if( isset( $_GET['location'] ) )
		$location = $_GET['location'];
	$plat_id = '';
	if( isset( $_GET['platid'] ) )
		$plat_id = intval($_GET['platid']);
	$payment = '';
	if( isset($_GET['paymethod']) )
		$paymethod = $_GET['paymethod'];
	$feature = '';
	if( isset($_GET['feature']) )
		$feature = $_GET['feature'];
	$pricestart = '';
	if( isset($_GET['pricestart']) )
		$pricestart = intval( $_GET['pricestart'] );
	$priceend = '';
	if( isset($_GET['priceend']) )
		$priceend = intval( $_GET['priceend'] );
	$tag = '';
	if( isset($_GET['tag']) )
		$tag = $_GET['tag'];

	$page = 1;
    if( isset( $_GET['p'] ) ){
        $page = intval( $_GET['p'] );
	}

	$productSearch = new ProductSearch();
	$searchType = NORMAL_QUERY;

	//clean keyword
	$keyword = $productSearch->CleanKeyword( $keyword );
	
	// move page var keyword forward
	$pageVars['keyword'] = $keyword;

	//determine the search type
	$filterArray = array();
	$additionalKeyword = array();
	if( !empty( $location ) ) {
		$searchType = FILTER_QUERY;
		$locationids = explode( ",", $location );

		//set page var
		$pageVars['location'] = $location;
		
		//read sub cities from citymap
		$locationFullIds = $locationids;
		foreach( $locationids as $lid ){
			if( isset( $cityMap[$lid] ) ){
				$locationFullIds = array_merge( $cityMap[$lid]['cityids'], $locationFullIds );
			}
		}
		$filterArray['location'] = $locationFullIds;
	}
	if( !empty( $plat_id ) ) {
		$searchType = FILTER_QUERY;
		if( intval($plat_id) == 0)
			$filterArray['plat_id'] = "$plat_id,99";
		else if( intval($plat_id) == 100)
			$filterArray['plat_id'] = "$plat_id,1000";
		else
			$filterArray['plat_id'] = array( intval($plat_id) );

		$pageVars['plat_id'] = $plat_id;
	}
	if( !empty( $category ) ) {
		$searchType = FILTER_QUERY;
		$filterArray['cate_id'] = array( intval($category) );

		$pageVars['cate_id'] = $category;
	}
	if( !empty( $paymethod ) ) {
		$searchType = FILTER_QUERY;
		$strPaymethod = implode( "," , $paymethod);

		//add field specified query to $keyword parameter
		$additionalKeyword['@paymethod'] = $strPaymethod;

		$pageVars['paymethod'] = $strPaymethod;
	}
	if( !empty( $feature ) ) {
		$searchType = FILTER_QUERY;
		$strFeature = implode( "," , $feature);

		//add field specified query to $keyword parameter
		$additionalKeyword['@feature'] = $strFeature;

		$pageVars['feature'] = $strFeature;
	}
	if( !empty( $tag ) ) {
		$searchType = FILTER_QUERY;

		//add field specified query to $keyword parameter
		$additionalKeyword['@tag'] = $tag;

		$pageVars['tag'] = $tag;
	}
	if( !empty( $pricestart ) && !empty( $priceend ) ) {
		$searchType = FILTER_QUERY;
		$strPriceRange = $pricestart."," .$priceend;

		//add field specified query to $keyword parameter
		$filterArray['price'] = $strPriceRange;

		$pageVars['pricestart'] = $pricestart;
		$pageVars['priceend'] = $priceend;
	}
	$isDesc = false;
	if( !empty( $sortby ) ) {
		$pageVars['sortby'] = $sortby;
		
		//parse sort
		//price0 is sort by price asc and price1 is sortby price desc
		$sortbyArray = explode( "-", $sortby );
		if( count($sortbyArray) == 2 && in_array( $sortbyArray[0], $validSortby ) ){
			$sortby = $sortbyArray[0];
			$isDesc = $sortbyArray[1] == "asc"? false : true;
		}
		else {
			$sortby = "";
		}

		if( $sortby != "" ){
			if( $searchType == FILTER_QUERY ) {
				$searchType = FILTER_SORT_QUERY;
			}
			else {
				$searchType = SORT_QUERY;
			}
		}
	}

	//assemble keyword
	foreach( $additionalKeyword as $key=>$value ) {
		$keyword .= " $key $value";
	}
	
	$result = array();
	switch( $searchType ) {
		case NORMAL_QUERY:
			$result = $productSearch->Query( $keyword, $page );
			break;
		case SORT_QUERY:
			$result = $productSearch->SortQuery( $keyword, $sortby, $page, $isDesc );
			break;
		case FILTER_QUERY:
			$result = $productSearch->MultiFilterQuery( $keyword, $filterArray, $page );
			break;
		case FILTER_SORT_QUERY:
			$result = $productSearch->MultiFilterAndSortQuery( $keyword, $filterArray, $sortby, $page, $isDesc );
			break;
		case RANGE_FILTER_SORT_QUERY:
			$result = $productSearch->MultiRangeFilterAndSortQuery( $keyword, $filterArray, $sortby, $page, $isDesc );
			break;
	}

	$pageVars['result'] = $result;
	if( $result['total'] > 0 && !empty($result['matchIds']) ) {
		$productDAO = new ProductDAO();
		$dbRes = $productDAO->GetProductInfoByIdList( $result['matchIds'] );
		
		$highLighRes = array();
		foreach( $dbRes as $row ) {
			$row['product_name_plain'] = $row['product_name'];
			//assemble field to highlight : shopname, shop description, nick, location, paymethod, tag, feature
			$arrToHighlight = array
				(
					//hard code here, need to be modified later
					'product_name' => $row['product_name'],
					'shop_name' => $row['shop_name'],
					'description' => $row['description']
				);
			// merge database and high light result array
			$row = array_merge( $row, $productSearch->BuildHighLight( $keyword, $arrToHighlight ) );
			$row['plat_name'] = $platformList[$row['plat_id']];

			//and set location and shopname

			$highLighRes[] = $row;
		}

		$pageVars['dbRes'] = $highLighRes;

		//get category information
		$categoryGroupByArray = $productSearch->GroupByQuery( $keyword, "cate_id" );
		$productCateDAO = new ProductCategoryDAO();
		$dbGroupByRes = $productCateDAO->GetProductCateInfoByIdList( array_keys( $categoryGroupByArray['matches'] ) );
		
		$dbGroupByResWithCount = array();
		foreach( $dbGroupByRes as $item ) {
			$item['count'] = $categoryGroupByArray['matches'][$item['id']]['count'];
			$dbGroupByResWithCount[] = $item;
		}

		$pageVars['dbGroupByRes'] = $dbGroupByResWithCount;
		//		print_r( $pageVars );

		// prepare page bar of search result
		//reset sortby's value
		if( isset( $pageVars['sortby'] ) )
			$sortby = $pageVars['sortby'];

		$currentURL = htmlspecialchars( $_SERVER["REQUEST_URI"] );
		$currentURL = preg_replace( '/&p=[0-9]+/', "", $currentURL );
		$pageObj = new Pager( $currentURL, $pageVars['result']['total'], SHOP_INFO_PER_PAGE, $page, UP_RESULT_PAGE );

		$pageVars['pagebar'] = $pageObj->getBar();
	}

	//at last insert search history
	$searchDao = GetSearchDAO();
	$param = array( 'user_ip' => $_SERVER['SERVER_ADDR'], 'keyword' => $pageVars['keyword'] );
	$searchDao->AddSearchHistory( $param );

    //search from search_history table, to get search suggestions
    $pageVars['suggestions'] = $searchDao->GetSuggestions( $pageVars['keyword'] );
}
?>
